/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.call;

import net.dgg.dggcloud.core.json.JsonUtil;
import net.dgg.dggcloud.core.minidao.hibernate.dao.IGenericBaseCommonDao;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.common.util.HttpUtility;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.dao.customer.CallRecordDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.ContactDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.SoundCommentDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.SoundPushRecordDao;
import net.dgg.dggcloud.service.jrcrm.entity.customer.CallRecord;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Contact;
import net.dgg.dggcloud.service.jrcrm.entity.customer.SoundComment;
import net.dgg.dggcloud.service.jrcrm.entity.customer.SoundPushRecord;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 录音管理业务处理层
 * @ClassName: CallRecordService
 * @Author: 罗金
 * @Date: 2017年11月03 14:34:05
 * @Version V1.0
 */

@Service
public class CallRecordService extends BaseService {

    @Autowired
    private CallRecordDao callRecordDao;
    @Autowired
    private SoundPushRecordDao soundPushRecordDao;
    @Autowired
    private SoundCommentDao soundCommentDao;
    @Resource(name = "miniDaoHiberCommonDao")
    protected IGenericBaseCommonDao repository;
    @Autowired
    private ContactDao contactDao;
    @Value("${cmsBaseUrl}")
    private String cmsBaseUrl;

    /**
     * 查询录音推送列表信息
     * @param map
     * @return
     */
    public List<Map> queryCallRecordList(Map map){
        return callRecordDao.queryCallRecordListByParams(map);
    }

    /**
     * 查询录音推送列表信息计数
     * @param map
     * @return
     */
    public Integer queryCallRecordListCount(Map map){
        return callRecordDao.queryCallRecordListCountByParams(map);
    }


    /**
     * 查询录音列表信息
     * @param map
     * @return
     */
    public List<Map> listQueryCallRecord(Map map){
        return callRecordDao.queryCallRecordByParams(map);
    }

    /**
     * 查询录音列表信息计数
     * @param map
     * @return
     */
    public Integer countQueryCallRecordList(Map map){
        return callRecordDao.queryCallRecordCountByParams(map);
    }


    /**
     * 录音详情
     * @param id
     * @return
     */
    public CallRecord findCallRecordById(Long id){
       return repository.get(CallRecord.class,id);
    }



    /**
     * 录音评价保存
     * @param soundComment
     * @param currUser
     */
    public void saveOrUpdate(SoundComment soundComment,User currUser){
        CallRecord call = repository.get(CallRecord.class,soundComment.getSoundId());
        SoundPushRecord sprd = null;
        if(soundComment.getPushRecordId()!=null)
            sprd = repository.get(SoundPushRecord.class, soundComment.getPushRecordId());
        if(sprd!=null){
            sprd.setIsListen(1);
            repository.saveOrUpdate(sprd);
        }
        Map map = new HashMap();
        map.put("soundId",soundComment.getSoundId());
        //根据评价详情表统计录音的平均分
        int score = soundCommentDao.querySoundCommentListAvgByParams(map);
        double s = (call.getLastSoundEstimateScore()*score+soundComment.getScore())/(double)(score+1);
        call.setLastSoundEstimateScore(s);
        call.setLastSoundEstimateUserName(currUser.getName());
        if(s>=9.0){
            call.setLastSoundEstimate("SOUND_EVALUATE_TAG1");//优秀
        }else if(s<8.0){
            call.setLastSoundEstimate("SOUND_EVALUATE_TAG3");//不合格
        }else{
            call.setLastSoundEstimate("SOUND_EVALUATE_TAG2");// 合格
        }
        if(soundComment.getScore()>=9.0){
            soundComment.setExt1("SOUND_EVALUATE_TAG1");//优秀
        }else if(soundComment.getScore()<8.0){
            soundComment.setExt1("SOUND_EVALUATE_TAG3");//不合格
        }else{
            soundComment.setExt1("SOUND_EVALUATE_TAG2");// 合格
        }
        repository.saveOrUpdate(call);
        Long newProductId = keyWorker.nextId();
        soundComment.setId(newProductId);
        soundComment.setCreaterId(currUser.getId());
        soundComment.setCreaterName(currUser.getName()+""+currUser.getLoginName());
        soundComment.setCreaterOrgId(currUser.getOrgId());
        soundComment.setCreateTime(new Date());
        repository.save(soundComment);
    }


    public List<Contact> queryContactListForJudgeRepeat(Map map){
        return contactDao.queryContactListForJudgeRepeat(map);
    }

    public Map queryRecordByIboss(Map params){
        Map map = new HashMap();
        try{
            params.put("startCount",params.get("start"));
            params.put("pageSize",params.get("length"));
            if(params.get("startTime")==null || "".equals(params.get("startTime").toString()) || params.get("endTime")==null || "".equals(params.get("endTime").toString())){
                //throw new BizException("由于录音数据量大,需要选择呼叫时间查询",1005);
                return map;
            }
            //防止页面传过来的值未  2018-11-7
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date st = sdf.parse(params.get("startTime").toString());
            Date en = sdf.parse(params.get("endTime").toString());
            params.put("startTime",sdf.format(st));
            params.put("endTime",sdf.format(en));

            String result = postRest( cmsBaseUrl +"/api/cms/record/v1/find_record_jr.do",params);
            Map provinceMap = JsonUtil.json2Obj(result, Map.class);
            if ("0".equals(provinceMap.get("code").toString())) {
                Map obj = JsonUtil.json2Obj(provinceMap.get("data").toString(), Map.class);
                return obj;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return map;
    }


    public static String postRest(String urlStr, Map<String, Object> paramsMap
    ) throws ClientProtocolException, IOException {
        String resultStr = "";
        HttpClient client = new DefaultHttpClient();

        // 创建一个POST请求
        HttpPost httpPost = new HttpPost(urlStr + "?encryptKey=ENCRYPT_KEY");
        // 设置连接超时时间(单位毫秒)
        HttpConnectionParams.setConnectionTimeout(httpPost.getParams(), 60000);
        // 设置读数据超时时间(单位毫秒)
        HttpConnectionParams.setSoTimeout(httpPost.getParams(), 60000);

        // 向HttpPost中加入参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Iterator iter = paramsMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            Object value = entry.getValue();
            nvps.add(new BasicNameValuePair(key, value == null ? "" : value.toString()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // 向服务器发送POST请求并获取服务器返回的结果
        HttpResponse response = client.execute(httpPost);
        // 返回的结果可能放到InputStream中。
        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream inputStream = response.getEntity().getContent();
            String line = "";
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            resultStr = buffer.toString();
            if (reader != null) {
                reader.close();
            }
        } else {
            System.out.println("请求服务器返回码："
                    + response.getStatusLine().getStatusCode());
        }

        return resultStr;
    }


}
